/**
* 版权声明：睿商(厦门)科技股份有限公司 版权所有 违者必究
* 日    期：2021-07-06
*/
package com.rzico.admin.controller.admin;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.rzico.admin.entity.Project;
import com.rzico.admin.service.ProjectActivityService;
import com.rzico.admin.service.ProjectExecuteService;
import com.rzico.admin.service.ProjectService;
import com.rzico.annotation.Log;
import com.rzico.base.BaseController;
import com.rzico.base.CommResult;
import com.rzico.core.entity.SysPlugin;
import com.rzico.core.entity.SysUser;
import com.rzico.core.plugin.MsgPlugin;
import com.rzico.core.service.SysPluginService;
import com.rzico.core.service.SysUserService;
import com.rzico.entity.Filter;
import com.rzico.entity.Pageable;
import com.rzico.entity.PageResult;
import com.rzico.admin.entity.Company;
import com.rzico.admin.service.CompanyService;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.Api;
import com.rzico.util.StringUtils;

import java.util.*;

/**
 * 企业资料
 *
 * @author Rzico Boot
 * @version 1.0
 * @date 2021-07-06
 */
@Api(description = "企业资料")
@RestController
@RequestMapping("/admin/company")
public class CompanyAdminController extends BaseController {

    @Autowired
    private CompanyService companyService;

    @Autowired
    private SysUserService sysUserService;


    @Autowired @Lazy
    protected ProjectService projectService;

    @Autowired @Lazy
    protected ProjectExecuteService projectExecuteService;

    @Autowired @Lazy
    protected ProjectActivityService projectActivityService;

    @Autowired @Lazy
    protected SysPluginService sysPluginService;

    /**
     * 分页查询企业资料
     *
     * @return
    */
    @ApiOperation("分页查询企业资料")
    @GetMapping("/list")
    @ApiImplicitParams({@ApiImplicitParam(name = "startDate", value = "开始时间", dataType = "String", paramType = "query") ,
            @ApiImplicitParam(name = "endDate", value = "结束时间", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "keyword", value = "搜索关键词", dataType = "String", paramType = "query") ,
            @ApiImplicitParam(name = "status", value = "状态(0.草稿,1.提交,2.审核,3.驳回)", dataType = "Integer", paramType = "query")
    })
    public CommResult<Company> list(Date startDate, Date endDate,Integer status,String keyword, Pageable pageable) {
        Map<String, Object> params = new HashMap<String, Object>();
        params = buildSortField(params, pageable);
        if (startDate!=null){
           params.put("startDate", startDate);
        }
        if (endDate!=null){
           params.put("endDate", DateUtils.addMilliseconds(DateUtils.addDays(endDate,1),-1));
        }


        if (keyword!=null){
            params.put("keyword", keyword);
        }


        if (status!=null){
            params.put("status", status);
        }
        SysUser sysUser = sysUserService.getCurrent();
        if (!sysUserService.isAdmin(sysUser)) {
            params.put("dataScopeId", sysUser.getId());
        }

        Page<Object> startPage = PageHelper.startPage(pageable.getPageNum(), pageable.getPageSize());
        List<Company> list = companyService.selectList(params);
        PageResult<Company> pageResult = new PageResult<Company>(list, startPage.getTotal(), pageable);
        return CommResult.success(pageResult);
    }

    /**
     * 查询单条企业资料
     *
     * @return
    */
    @ApiOperation("查询单条企业资料")
    @GetMapping("/find/{id}")
    public CommResult<Company> find(@PathVariable String id) {
        Company result = companyService.findById(id);

        Map<String,Object> data = new HashMap<>();
        data.put("company",result);
        return CommResult.success(data);

    }

    /**
     * 保存企业资料
     *
     * @param company
     * @return
     */
    @ApiOperation("保存企业资料")
    @PostMapping("/save")
    public CommResult<Company> save(@RequestBody Company company) {
        int affectCount = companyService.insert(company);
        if (affectCount <= 0) {
            return CommResult.error();
        }
        Company result = companyService.findById(company.getId());
        return CommResult.success(result);

    }


    /**
     * 批量删除企业资料
     *
     * @param ids
     * @return
     */
    @Log(desc = "批量删除企业资料", type = Log.LOG_TYPE.DEL)
    @ApiOperation("批量删除企业资料,ids用逗号拼接")
    @PostMapping("/del/{ids}")
    public CommResult<Company> del(@PathVariable String ids) {

        companyService.deleteByIds(ids.split(","));
        return CommResult.success();
    }


    /**
     * 发送提醒
     *
     * @return
     */
    @Log(desc = "发送提醒", type = Log.LOG_TYPE.DEL)
    @ApiOperation("发送提醒")
    @PostMapping("/sendMsg")
    public CommResult<Company> sendMsg() {

        Map<String,Object> params = new HashMap<>();
        params.put("status",2);

        SysPlugin sysPlugin = sysPluginService.getEnabledPlugin("10200",SysPlugin.MSGPLUGIN);

        if (sysPlugin==null) {
            return CommResult.error("插件没有安装");
        }

        List<Project> projectList = projectService.selectList(params);

        for (Project proj:projectList) {
            try {

                Map<String,Object> wparams = new HashMap<>();
                wparams.put("projectId",proj.getId());
                wparams.put("startDate", org.apache.commons.lang3.time.DateUtils.truncate(new Date(), Calendar.DATE));
                wparams.put("endDate",org.apache.commons.lang3.time.DateUtils.addDays(org.apache.commons.lang3.time.DateUtils.truncate(new Date(),Calendar.DATE),1));
                Integer w1 = projectExecuteService.selectRowCount(wparams);
                Integer w2 = projectActivityService.selectRowCount(wparams);

                if (w1>0 && w2>0) {
                    continue;
                }

                SysUser sysUser = sysUserService.selectByPrimaryKey(proj.getUserId());

                String msg = "【龙山双创】您项目"+proj.getProjectName()+"的月度活动报表没有上传，请尽快处理";
                try {
                    MsgPlugin msgPlugin = sysPluginService.getMsgPlugin(sysPlugin.getPluginId());
                    msgPlugin.sendMsg(sysPlugin,"13860431130",msg);
                } catch (Exception e) {

                }

            } catch (Exception e) {
                logger.error(e.getMessage());
            }

        }
        return CommResult.success();
    }

    /**
     * 更新企业资料
     *
     * @param company
     * @return
     */
    @Log(desc = "更新企业资料", type = Log.LOG_TYPE.UPDATE)
    @ApiOperation("更新企业资料")
    @PostMapping("/update")
    public CommResult<Company> update(@RequestBody Company company) {
        int affectCount = companyService.updateByPrimaryKeySelective(company);
        if (affectCount <= 0){
            return CommResult.error();
        }
        Company result = companyService.findById(company.getId());
        return CommResult.success(result);
    }

    /**
     * 提交企业资料
     * @param companyId
     * @return
     */
    @ApiOperation("提交企业资料")
    @PostMapping("/submit")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "companyId", value = "企业资料id", dataType = "Long", paramType = "query")
    })
    public CommResult<Company> submit(Long companyId) {
        int affectCount = companyService.submit(companyId);
        if (affectCount <= 0){
            return CommResult.error();
        }
        return CommResult.success();
    }

    /**
     * 审核企业资料
     * @param companyId
     * @return
     */
    @ApiOperation("审核企业资料")
    @PostMapping("/adopt")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "companyId", value = "企业资料id", dataType = "Long", paramType = "query")
    })
    public CommResult<Company> adopt(Long companyId) {
        int affectCount = companyService.adopt(companyId);
        if (affectCount <= 0){
            return CommResult.error();
        }
        return CommResult.success();
    }

    /**
     * 驳回企业资料
     * @param companyId
     * @return
     */
    @ApiOperation("驳回企业资料")
    @PostMapping("/reject")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "companyId", value = "企业资料id", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "rejectText", value = "驳回理由", dataType = "String", paramType = "query")
    })
    public CommResult<Company> reject(Long companyId,String rejectText) {
        int affectCount = companyService.reject(companyId,rejectText);
        if (affectCount <= 0){
            return CommResult.error();
        }
        return CommResult.success();
    }
}
